import { Toast } from 'vant'
import { computed, inject, reactive,getCurrentInstance } from 'vue'
import {debounce,checkObjectEmpty} from '../../../utils/common.js'
import {BalanceApi} from '../../../api/index.js'
import { useRouter } from 'vue-router'

function useGiftCard(){
    const {props,proxy} = getCurrentInstance()
    const router = useRouter()
    const vueState = inject('vueState')
    const state = reactive({
        pageError:false,
        rates:[],
        active:0,
        fsize:window.fsize,
        form:{
            email:'',
            name:'',
            phone:''
        }
    })
    const failureModalData = reactive({
        show:false,
    })
    const channelInfo = computed(()=>{
        return checkObjectEmpty(JSON.parse(props.channel)) ? vueState.pageInfo.withdrawChannel : JSON.parse(props.channel)
    })
    const cardName = computed(()=>{
        switch (channelInfo.value?.type) {
            case 'amazon':
                return 'Amazon'
            case 'flipkart':
                return 'Flipkart'
            case 'googlePlay':
                return 'Google Play'
            case 'americanas': //to:langlang   s
                return 'Americanas'
            case 'centauro':
                return 'Centauro' 
            case 'rewardLink':
                return 'REWARD LINK' //to:langlang  e
            default:
                return ''
        }
    })
    
    const GiftCardModalData = reactive({
            show:false,
            submit:debounce(async(field)=> {
                const {email,name,phone} = field
                state.form.email = email.model
                state.form.name = name.model
                state.form.phone = phone.model
                try{
                    if(name.state && email.state && phone.state){
                        await BalanceApi.GiftCard({
                            bundleId:vueState.bundle,
                            name:state.form.name,
                            email:state.form.email,
                            amount:activeItem.value.coin,
                            realName:state.form.name,
                            channelId:channelInfo.value.channelId,
                            type:channelInfo.value.type,
                            utid: activeItem.value.utid //to:langlang   新增
                        })
                        GiftCardModalData.show = false
                        window.SDKPostMessage({
                            event:'h5_open_page',
                            data:{
                                target:'reward_pop',
                                data:{
                                    from:'giftCard',
                                }
                            }
                        })
                        window.trackEvent({pageTitle:`${channelInfo.value?.type}Page`,ev:'clickSubimtButton',remarks:`status:success,email:${state.form.email},name:${state.form.name},amount:${activeItem.value.money}`})
                    }else{
                        Toast(proxy.$t('Please fill in the information'))
                    }
                }catch(e){
                    if(e?.data?.code === 201022){
                        Toast.clear()
                        failureModalData.show = true
                        window.trackEvent({pageTitle:'withdrawpage',ev:'showSwitchingPop',remarks:`Type=${channelInfo.value?.type}`})
                    }
                    window.trackEvent({pageTitle:`${channelInfo.value.type}Page`,ev:'clickSubimtButton',remarks:'status:others'})
                    console.log(e);
                }
                
            },500)
    })
    const activeItem = computed(()=>{
        return state.rates[state.active]
    })
    const getData = async()=> {
        Toast.loading({duration:0,message:`${proxy.$t('Loading')}...`})
        try{
            const {toBalanceRate:{channelRateVos=[]}} = await BalanceApi.QueryGiftCardInfo({channelType:channelInfo.value?.type})
            state.pageError = false
            state.rates = channelRateVos.map((item)=>{
                return {
                    coin:item.coin,
                    money:parseInt(item.money/100),
                    utid: item.utid  //to:langlang  新增
                }
            })
            Toast.clear()
        }catch(e){
            state.pageError = true
            console.log(e);
            setTimeout(()=>{
                Toast.clear()
            },3000)
        }
    }
    const goWithdrawHistory = ()=> {
        if(!vueState.pageInfo.mobile){
            window.SDKPostMessage({
                event:'h5_open_page',
                data:{
                    target:'bind_mobile',
                    data:{
                        page:'withdrawpage',
                        showEvent:'showwithdrawbind',
                        clickEvent:'clickwithdrawbind'
                    }
                }
            })
            return
        }
        router.push({name:'withdrawRecord'})
    }
    const selectItem = (index)=>{
        state.active = index
        window.trackEvent({pageTitle:`${channelInfo.value.type}Page`,ev:'clickGiftCardGear',remarks:`${vueState.countryInfo.currencySymbol}${activeItem.value.money}`})
    }
    const submit = ()=> {
        window.trackEvent({pageTitle:`${channelInfo.value.type}Page`,ev:'clickBuyButton'})
        if(!vueState.pageInfo.mobile){
            window.SDKPostMessage({
                event:'h5_open_page',
                data:{
                    target:'bind_mobile',
                    data:{
                        page:'withdrawpage',
                        showEvent:'showwithdrawbind',
                        clickEvent:'clickwithdrawbind'
                    }
                }
            })
            return
        }
        if(vueState.pageInfo.totalCoin < activeItem.value.coin){
            Toast(proxy.$t('Your balance is insufficient'))
            return
        }
        if(!channelInfo.value.flag){
            failureModalData.show = true
            window.trackEvent({pageTitle:'withdrawpage',ev:'showSwitchingPop',remarks:`Type=${channelInfo.value.type}`})
            return
        }
        GiftCardModalData.show = true
    }
    return {
        state,
        getData,
        activeItem,
        selectItem,
        submit,
        GiftCardModalData,
        channelInfo,
        cardName,
        failureModalData,
        goWithdrawHistory
    }
}

export {useGiftCard}